﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

using ExamDemo.Data;
using ExamDemo.Models;

namespace tinyTalk.Controllers
{
    public class UsersController : Controller
    {
        public ExamDemoDb db = new ExamDemoDb();

        // GET: Users
        public ActionResult Login(FormCollection collection)
        {
            return View();

        }
        /// <summary>
        /// 完成登录
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult LoginDone(FormCollection collection)
        {
            var username = collection["username"];
            var password = collection["password"];
            Console.WriteLine(username);
            Console.WriteLine(password);

            var userName = db.Users.Where(x => x.Username == username).SingleOrDefault();
            var userPassword = db.Users.Where(x => x.Password == password);
            Console.WriteLine(userName);
            Console.WriteLine(userPassword);

            if (userName != null && userPassword != null)
            {
                Session["username"] = userName;
                var userId = userName.Id;
                Session["Id"] = userId;

                return Json(new
                {
                    code = 200,
                    msg = "登陆成功！"
                });
            }
            else
            {
                return Json(new
                {
                    code = 1000,
                    msg = "用户名或密码错误！"
                });
            };
        }
        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }
        /// <summary>
        /// 完成注册
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult RegisterDone(FormCollection collection)
        {
            var username = collection["username"];
            var password = collection["password"];
            var surePassword = collection["surePasswords"];

            if (username.Length > 0 && password.Length > 0 && surePassword.Length > 0 && password == surePassword)
            {
                var userName = db.Users.Where(x => x.Username == username).FirstOrDefault();

                if (userName != null)
                {
                    return Json(new
                    {
                        code = 1000,
                        msg = "用户名已存在!"
                    });
                }
                else
                {
                    db.Users.Add(new Users
                    {
                        Username = username,
                        Password = password,
                        CreateAt = DateTime.Now,
                        UpdateAt = DateTime.Now,
                        Version = 0,
                    });
                    db.SaveChanges();
                    return Json(new
                    {
                        code = 200,
                        msg = "注册成功！"
                    });
                };
            }
            else
            {
                Console.WriteLine("Passwords are not equal. Please try again！");
            };
            return View();
        }

        // GET: Users/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // GET: Users/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Users/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Username,Password")] Users user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(user);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Username,Password")] Users user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        // GET: Users/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Users user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
